package cn.haohaowo.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

import cn.haohaowo.annotation.MyBatisRepository;

@Configuration
@MapperScan(annotationClass=MyBatisRepository.class, basePackages={"cn.haohaowo"}, sqlSessionFactoryRef="mybatisSqlSessionFactory")
public class MybatisDBConfiguration {
	
	private Logger log = LoggerFactory.getLogger(MybatisDBConfiguration.class);
	
	@Autowired
	private CommonProperties commonProperties;
	
	@Bean(name="mybatisDataSource", destroyMethod="close")
	public DataSource getDataSource() {
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setDriverClassName(commonProperties.getJdbcDriver());
		basicDataSource.setUrl(commonProperties.getJdbcUrl());
		basicDataSource.setUsername(commonProperties.getJdbcUser());
		basicDataSource.setPassword(commonProperties.getJdbcPassword());
		
		return basicDataSource;
	}
	
	@Bean(name="mybatisSqlSessionFactory")
	public SqlSessionFactory getSqlSessionFactory(@Qualifier("mybatisLazyConnectionDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		sqlSessionFactoryBean.setTypeAliasesPackage("com.haohaowo.bean");
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/haohaowo/dao/mybatis/*Mapper.xml"));
		sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath*:/mybatis-config/xml"));
		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
		
		return sqlSessionFactory;
	}
	
	@Bean(name="mybatisTransactionManager")
	public DataSourceTransactionManager getTransactionManager(@Qualifier("mybatisLazyConnectionDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean(name="mybatisLazyConnectionDataSource")
	public DataSource getLazyConnectionDataSource(@Qualifier("mybatisDataSource") DataSource dataSource) {
		return new LazyConnectionDataSourceProxy(dataSource);
	}
}
